package cn.s1995.sloth.common.core.i18n;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.LocaleResolver;

import java.util.Locale;

/**
 * I18nCustomLocaleResolver
 *
 * @author Lex
 * @description 自定义本地化解析器
 * @date 2024/03/11 16:51
 */
public class I18nCustomLocaleResolver implements LocaleResolver {

    /**
     * 本地化解析器：根据自定义逻辑来解析语言环境
     * <pre>
     *   1. 获取语言参数值的顺序 query > cookie > custom header > header -> Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
     * </pre>
     * @param request
     * @return
     */
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String languageName = I18nConfig.LANGUAGE;

        String languageValue = request.getParameter(languageName);
        // if (languageValue == null || languageValue.isEmpty()) {
        //     languageValue = WebUtils.getCookieVal(request, languageName);
        // }
        if (languageValue == null || languageValue.isEmpty()) {
            languageValue = request.getHeader(languageName);
        }
        if (languageValue == null || languageValue.isEmpty()) {
            languageValue = request.getHeader("Accept-Language");
        }

        // 默认语言环境
        Locale defaultLocale = Locale.ENGLISH;

        if (languageValue == null || languageValue.isEmpty()) {
            return defaultLocale;
        }

        Locale requestedLocale = Locale.forLanguageTag(languageValue);

        // // 根据实际情况调整逻辑
        // if (requestedLocale.equals(Locale.TRADITIONAL_CHINESE)) {
        //     // 如果请求的是繁体中文，但没有对应的资源文件，可以转换为简体中文
        //     return Locale.SIMPLIFIED_CHINESE;
        // } else {
        //     // 其他情况，根据请求的语言环境来决定
        //     return requestedLocale;
        // }

        return requestedLocale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}
